<template>
  <div>
    <!-- 头部 -->
    <hm-header>登录</hm-header>
    <hm-logo></hm-logo>

    <!-- 用户名 -->
    <hm-input
      ref="username"
      type="text"
      placeholder="请输入用户名"
      v-model="username"
      :rule="/^1\d{4,10}$/"
      message="用户格式不对"
    ></hm-input>
    <!-- 密码 -->
    <hm-input
      ref="password"
      type="password"
      placeholder="请输入密码"
      v-model="password"
      :rule="/^\d{3,12}$/"
      message="用户密码格式不对"
    ></hm-input>

    <!-- 按钮 -->
    <hm-button @click="login">登录</hm-button>

    <!-- 去注册的连接 -->
    <div class="go-register">
      没有账号？去
      <router-link class="link" to="/register">注册</router-link>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  data() {
    return {
      username: '10086',
      password: '123'
    }
  },
  created() {
    console.log(this.$route.params)
  },

  methods: {
    login() {
      if (!this.$refs.username.validate(this.username)) return
      if (!this.$refs.password.validate(this.password)) return

      // 发送请求
      axios
        .post('/login', {
          username: this.username,
          password: this.password
        })
        .then(res => {
          console.log('登录', res)
          const { statusCode, data } = res.data
          if (statusCode === 200) {
            this.$toast.success('登录成功')

            localStorage.setItem('token', data.token)
            localStorage.setItem('user_id', data.user.id)
            this.$router.push('/user')
          } else {
            Toast.fail('登录失败')
          }
        })
    }
  }
}
</script>

<style lang='less' scoped>
.go-register {
  padding: 0 20px;
  font-size: 18px;
  text-align: right;
  .link {
    color: green;
  }
}
</style>
